package com.codingapi.p2p.server.handler;

import com.codingapi.p2p.server.utils.SocketUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * create by lorne on 2018/3/13
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter{


    private Logger logger = LoggerFactory.getLogger(DiscardServerHandler.class);



    private static ChannelHandlerContext client1;

    private static ChannelHandlerContext client2;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        InetSocketAddress socketAddress =  (InetSocketAddress)ctx.channel().remoteAddress();
        logger.info("connection-->"+socketAddress.getHostName()+","+socketAddress.getPort());

        if(client1==null) {
            client1 = ctx;
        }else{
            client2 = ctx;
            //send msg
            sendMsg(client2,(InetSocketAddress)client2.channel().remoteAddress(),(InetSocketAddress)client1.channel().remoteAddress());
            sendMsg(client1,(InetSocketAddress)client1.channel().remoteAddress(),(InetSocketAddress)client2.channel().remoteAddress());
        }
    }

    private void sendMsg(ChannelHandlerContext ctx,InetSocketAddress self,InetSocketAddress remote){
        SocketUtils.send(ctx.channel(),(self.getHostName()+":"+remote.getHostName()+":"+remote.getPort()).getBytes());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        logger.info("disconnection-->");
        if(ctx==client1){
            client1 = null;
        }
        if(ctx==client2){
            client2 = null;
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        logger.info("read-->");
    }
}
